import log4js from 'log4js';
import type { LoggerConfig } from '../types/logger.js';
import { config } from '../config/env.js';

// 日志配置
const loggerConfig: LoggerConfig = {
  appenders: {
    console: {
      type: 'console',
      layout: {
        type: 'pattern',
        pattern: '%[[%d{yyyy-MM-dd hh:mm:ss.SSS}] [%p] [%c]%] - %m',
      },
    },
    info: {
      type: 'dateFile',
      filename: `${config.log.dir}/info.log`,
      pattern: 'yyyy-MM-dd',
      compress: true,
      maxLogSize: 10485760, // 10MB
      backups: 10,
      keepFileExt: true,
      numBackups: 30, // 保留30天的日志
      layout: {
        type: 'pattern',
        pattern: '[%d{yyyy-MM-dd hh:mm:ss.SSS}] [%p] [%c] - %m',
      },
    },
    error: {
      type: 'dateFile',
      filename: `${config.log.dir}/error.log`,
      pattern: 'yyyy-MM-dd',
      compress: true,
      maxLogSize: 10485760, // 10MB
      backups: 10,
      keepFileExt: true,
      numBackups: 30, // 保留30天的日志
      layout: {
        type: 'pattern',
        pattern: '[%d{yyyy-MM-dd hh:mm:ss.SSS}] [%p] [%c] - %m',
      },
    },
    access: {
      type: 'dateFile',
      filename: `${config.log.dir}/access.log`,
      pattern: 'yyyy-MM-dd',
      compress: true,
      maxLogSize: 10485760, // 10MB
      backups: 10,
      keepFileExt: true,
      numBackups: 30, // 保留30天的日志
      layout: {
        type: 'pattern',
        pattern: '[%d{yyyy-MM-dd hh:mm:ss.SSS}] [%p] [%c] - %m',
      },
    },
  },
  categories: {
    default: {
      appenders: ['console', 'info'],
      level: config.app.isProd ? 'info' : 'debug',
    },
    error: {
      appenders: ['console', 'error'],
      level: 'error',
    },
    access: {
      appenders: ['console', 'access'],
      level: config.log.level,
    },
  },
  disableClustering: true, // 禁用集群模式以提高性能
};

// 配置 log4js
log4js.configure(loggerConfig);

// 创建日志记录器
class Logger {
  private _logger: log4js.Logger;

  constructor(category: string = 'default') {
    this._logger = log4js.getLogger(category);
  }

  get logger(): log4js.Logger {
    return this._logger;
  }

  trace(message: string, ...args: unknown[]): void {
    this._logger.trace(message, ...args);
  }

  debug(message: string, ...args: unknown[]): void {
    this._logger.debug(message, ...args);
  }

  info(message: string, ...args: unknown[]): void {
    this._logger.info(message, ...args);
  }

  warn(message: string, ...args: unknown[]): void {
    this._logger.warn(message, ...args);
  }

  error(message: string, ...args: unknown[]): void {
    this._logger.error(message, ...args);
  }

  fatal(message: string, ...args: unknown[]): void {
    this._logger.fatal(message, ...args);
  }

  access(message: string, ...args: unknown[]): void {
    this._logger.info(message, ...args);
  }
}

// 创建不同类型的日志记录器实例
const logger = new Logger('default');

// 导出日志记录器和中间件
export { logger, log4js };
